# coding: utf-8
from ZipUtil import *
from ApkUtg import *
from ApkState import *
from CvUtil import ImageProcess as ip
from LogUtil import *
import sys
import cv2


class CurrentApk(object):
    def __init__(self, apk_path, temp_path, enable_image_filter=False, unzip=False):
        self.apk_path = apk_path
        self.temp_path = temp_path
        self.is_valid_apk = True
        self.enable_image_filter = enable_image_filter
        self.package_name = self.get_package_name()
        if unzip:
            self.unzip_apk()
        self.image_dict = self.read_resImage()
        self.apk_name = self.apk_path[self.apk_path.rfind('\\') + 1:]
        self.utg = UTG(self.apk_name)
        self.state_list = []
        self.state_stack = []
        if self.enable_image_filter:
            self.image_filter()

    def get_package_name(self):
        apk_INFO = os.popen('aapt dump badging ' + self.apk_path).read()
        package_name = apk_INFO[apk_INFO.find("package: name='") + 15:apk_INFO.find("versionCode") - 2]
        return package_name

    def unzip_apk(self):
        try:
            z = ZFile(self.apk_path)
            z.extract_to(self.temp_path + self.apk_path[self.apk_path.rfind('\\') + 1:])
            z.close()
            logging.info('Unzip apk success !')
        except:
            logging.error('Unzip apk fail !')

    def read_resImage(self):
        image_dict = {}
        rootdir = self.temp_path + self.apk_path[self.apk_path.rfind('\\') + 1:] + '\\'
        for parent, dirnames, filenames in os.walk(rootdir):
            for filename in filenames:
                file_path = os.path.join(parent, filename)
                if file_path.endswith('png'):
                    image_dict[file_path] = 0
        if len(image_dict) < 10:
            logging.error('%d image files founded, less than 10 !', len(image_dict))
            logging.error('RESOURCE FILE UNSATISFIED, HALTING !')
            self.is_valid_apk = False
        else:
            logging.info('%d image files founded !', len(image_dict))
        return image_dict

    def image_filter(self):
        image_dict_filtered = {}
        for img in self.image_dict.keys():
            try:
                size = cv2.imread(img).shape
            except:
                continue
            p_f = 0
            if size[0] >= size[1]:
                proportion = float(size[0]) / float(size[1])
            else:
                proportion = float(size[1]) / float(size[0])
            if proportion < 2.0:
                p_f = 1
            if size[0] > 45 and size[1] > 45 and size[0] <= 355 and size[1] <= 355 and p_f == 1:
                image_dict_filtered[img] = 0
                # if True:
                #     image_dict_filtered[img] = 0
        logging.info('%d image files founded after filtering !', len(image_dict_filtered))
        self.image_dict = image_dict_filtered

    def output_state_info(self):
        state_info = []
        for state in self.state_list:
            each_state_info = {
                "time_name": state.time_name,
                "md5_name": state.md5_name,
                "image_match": state.position_dict
            }
            state_info.append(each_state_info)
        return state_info
